/**
 * 消息过滤器工具
 * 用于过滤和清理AI响应中的错误信息、敏感内容和格式问题
 */

// 错误模式定义
const ERROR_PATTERNS = {
  // JSON错误格式
  jsonError: {
    pattern: /##?\{[^}]*["']errorCode["'][^}]*\}/g,
    replacement: ''
  },
  
  // 直接的JSON错误对象
  directJsonError: {
    pattern: /\{[^}]*["']errorCode["'][^}]*\}/g,
    replacement: ''
  },
  
  // API错误响应
  apiError: {
    pattern: /\{[^}]*["']error["']\s*:\s*["'][^"']*["'][^}]*\}/g,
    replacement: ''
  },
  
  // 系统错误信息
  systemError: {
    pattern: /\[ERROR\].*?\[\/ERROR\]/gs,
    replacement: ''
  },
  
  // 调试信息
  debugInfo: {
    pattern: /\[DEBUG\].*?\[\/DEBUG\]/gs,
    replacement: ''
  },
  
  // 内部错误代码
  internalError: {
    pattern: /Internal Error Code: \d+/g,
    replacement: ''
  },
  
  // 堆栈跟踪信息
  stackTrace: {
    pattern: /at\s+[\w\.]+\s*\([^)]*\)/g,
    replacement: ''
  }
}

// 敏感内容模式
const SENSITIVE_PATTERNS = {
  // API密钥
  apiKey: {
    pattern: /(?:api[_-]?key|token|secret)[\s=:]["']?[a-zA-Z0-9_-]{20,}["']?/gi,
    replacement: '[API密钥已隐藏]'
  },
  
  // 个人信息（身份证号）
  idCard: {
    pattern: /\b\d{15}|\d{17}[\dxX]\b/g,
    replacement: '[身份证号已隐藏]'
  },
  
  // 手机号
  phone: {
    pattern: /\b1[3-9]\d{9}\b/g,
    replacement: '[手机号已隐藏]'
  },
  
  // 邮箱地址
  email: {
    pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,
    replacement: '[邮箱已隐藏]'
  }
}

// 格式问题模式
const FORMAT_PATTERNS = {
  // 多余的换行
  excessiveNewlines: {
    pattern: /\n{3,}/g,
    replacement: '\n\n'
  },
  
  // 多余的空格
  excessiveSpaces: {
    pattern: /[ \t]{3,}/g,
    replacement: '  '
  },
  
  // 不完整的markdown
  incompleteMarkdown: {
    pattern: /```[^`]*$/g,
    replacement: '```'
  },
  
  // 损坏的HTML标签
  brokenHtmlTags: {
    pattern: /<[^>]*$/g,
    replacement: ''
  }
}

// 医疗内容验证模式
const MEDICAL_PATTERNS = {
  // 不当的诊断声明
  diagnosis: {
    pattern: /您?患有|确诊为|诊断为/g,
    replacement: '可能存在',
    warning: '检测到诊断性语言，已调整为建议性表述'
  },
  
  // 药物剂量建议
  dosage: {
    pattern: /服用\s*\d+[毫克片粒]/g,
    replacement: '请遵医嘱服用',
    warning: '检测到具体剂量建议，已替换为通用建议'
  },
  
  // 紧急情况处理
  emergency: {
    pattern: /立即|马上|紧急/g,
    replacement: '尽快',
    warning: '检测到紧急性表述，建议用户及时就医'
  }
}

/**
 * 消息过滤器类
 */
export class MessageFilter {
  constructor(options = {}) {
    this.options = {
      removeErrors: true,
      filterSensitive: true,
      fixFormat: true,
      validateMedical: true,
      logFiltering: false,
      ...options
    }
    
    this.filteringLog = []
  }

  /**
   * 过滤消息内容
   * @param {string} content - 原始消息内容
   * @param {Object} context - 上下文信息
   * @returns {Object} 过滤结果
   */
  filter(content, context = {}) {
    if (!content || typeof content !== 'string') {
      return {
        content: content || '',
        filtered: false,
        warnings: [],
        log: []
      }
    }

    const result = {
      content,
      filtered: false,
      warnings: [],
      log: []
    }

    // 1. 移除错误信息
    if (this.options.removeErrors) {
      result.content = this.removeErrors(result.content, result)
    }

    // 2. 过滤敏感内容
    if (this.options.filterSensitive) {
      result.content = this.filterSensitive(result.content, result)
    }

    // 3. 修复格式问题
    if (this.options.fixFormat) {
      result.content = this.fixFormat(result.content, result)
    }

    // 4. 验证医疗内容
    if (this.options.validateMedical && context.isMedical) {
      result.content = this.validateMedical(result.content, result)
    }

    // 5. 最终清理
    result.content = this.finalCleanup(result.content)

    // 记录过滤日志
    if (this.options.logFiltering && result.log.length > 0) {
      this.filteringLog.push({
        timestamp: Date.now(),
        context,
        log: result.log,
        warnings: result.warnings
      })
    }

    return result
  }

  /**
   * 移除错误信息
   */
  removeErrors(content, result) {
    let filtered = content
    let hasChanges = false

    Object.entries(ERROR_PATTERNS).forEach(([key, pattern]) => {
      const matches = filtered.match(pattern.pattern)
      if (matches) {
        filtered = filtered.replace(pattern.pattern, pattern.replacement)
        hasChanges = true
        result.log.push(`移除${key}错误信息: ${matches.length}处`)
      }
    })

    if (hasChanges) {
      result.filtered = true
      
      // 如果移除错误后内容为空或只有空白字符
      if (!filtered.trim()) {
        filtered = '抱歉，服务暂时遇到问题，请稍后重试。'
        result.warnings.push('原始内容被完全过滤，使用默认错误提示')
      }
    }

    return filtered
  }

  /**
   * 过滤敏感内容
   */
  filterSensitive(content, result) {
    let filtered = content
    let hasChanges = false

    Object.entries(SENSITIVE_PATTERNS).forEach(([key, pattern]) => {
      const matches = filtered.match(pattern.pattern)
      if (matches) {
        filtered = filtered.replace(pattern.pattern, pattern.replacement)
        hasChanges = true
        result.log.push(`过滤${key}敏感信息: ${matches.length}处`)
        result.warnings.push(`检测到${key}敏感信息，已自动隐藏`)
      }
    })

    if (hasChanges) {
      result.filtered = true
    }

    return filtered
  }

  /**
   * 修复格式问题
   */
  fixFormat(content, result) {
    let filtered = content
    let hasChanges = false

    Object.entries(FORMAT_PATTERNS).forEach(([key, pattern]) => {
      const originalLength = filtered.length
      filtered = filtered.replace(pattern.pattern, pattern.replacement)
      
      if (filtered.length !== originalLength) {
        hasChanges = true
        result.log.push(`修复${key}格式问题`)
      }
    })

    if (hasChanges) {
      result.filtered = true
    }

    return filtered
  }

  /**
   * 验证医疗内容
   */
  validateMedical(content, result) {
    let filtered = content
    let hasChanges = false

    Object.entries(MEDICAL_PATTERNS).forEach(([key, pattern]) => {
      const matches = filtered.match(pattern.pattern)
      if (matches) {
        filtered = filtered.replace(pattern.pattern, pattern.replacement)
        hasChanges = true
        result.log.push(`调整${key}医疗表述: ${matches.length}处`)
        if (pattern.warning) {
          result.warnings.push(pattern.warning)
        }
      }
    })

    if (hasChanges) {
      result.filtered = true
    }

    return filtered
  }

  /**
   * 最终清理
   */
  finalCleanup(content) {
    return content
      .trim()
      .replace(/^\s*[\r\n]+/gm, '') // 移除行首空白
      .replace(/[\r\n]+\s*$/gm, '') // 移除行尾空白
      .replace(/\n{3,}/g, '\n\n') // 限制连续换行
  }

  /**
   * 获取过滤统计
   */
  getFilteringStats() {
    const stats = {
      totalFiltered: this.filteringLog.length,
      errorFiltering: 0,
      sensitiveFiltering: 0,
      formatFixing: 0,
      medicalValidation: 0
    }

    this.filteringLog.forEach(entry => {
      entry.log.forEach(logItem => {
        if (logItem.includes('错误信息')) stats.errorFiltering++
        if (logItem.includes('敏感信息')) stats.sensitiveFiltering++
        if (logItem.includes('格式问题')) stats.formatFixing++
        if (logItem.includes('医疗表述')) stats.medicalValidation++
      })
    })

    return stats
  }

  /**
   * 清除过滤日志
   */
  clearLog() {
    this.filteringLog = []
  }

  /**
   * 添加自定义过滤规则
   */
  addCustomPattern(category, name, pattern, replacement, warning = null) {
    const patterns = {
      error: ERROR_PATTERNS,
      sensitive: SENSITIVE_PATTERNS,
      format: FORMAT_PATTERNS,
      medical: MEDICAL_PATTERNS
    }

    if (patterns[category]) {
      patterns[category][name] = {
        pattern,
        replacement,
        ...(warning && { warning })
      }
    }
  }
}

/**
 * 内容安全检查器
 */
export class ContentSafetyChecker {
  static checkSafety(content) {
    const issues = []
    
    // 检查是否包含错误信息
    Object.entries(ERROR_PATTERNS).forEach(([key, pattern]) => {
      if (pattern.pattern.test(content)) {
        issues.push({
          type: 'error',
          category: key,
          severity: 'high',
          message: `包含${key}错误信息`
        })
      }
    })

    // 检查敏感内容
    Object.entries(SENSITIVE_PATTERNS).forEach(([key, pattern]) => {
      if (pattern.pattern.test(content)) {
        issues.push({
          type: 'sensitive',
          category: key,
          severity: 'medium',
          message: `包含${key}敏感信息`
        })
      }
    })

    // 检查医疗内容
    Object.entries(MEDICAL_PATTERNS).forEach(([key, pattern]) => {
      if (pattern.pattern.test(content)) {
        issues.push({
          type: 'medical',
          category: key,
          severity: 'medium',
          message: `包含不当${key}表述`
        })
      }
    })

    return {
      safe: issues.length === 0,
      issues,
      riskLevel: this.calculateRiskLevel(issues)
    }
  }

  static calculateRiskLevel(issues) {
    if (issues.length === 0) return 'safe'
    
    const highSeverityCount = issues.filter(issue => issue.severity === 'high').length
    const mediumSeverityCount = issues.filter(issue => issue.severity === 'medium').length
    
    if (highSeverityCount > 0) return 'high'
    if (mediumSeverityCount > 2) return 'medium'
    return 'low'
  }
}

// 创建全局消息过滤器实例
export const globalMessageFilter = new MessageFilter({
  removeErrors: true,
  filterSensitive: true,
  fixFormat: true,
  validateMedical: true,
  logFiltering: true
})

// 导出便捷函数
export const filterMessage = (content, context) => globalMessageFilter.filter(content, context)
export const checkContentSafety = (content) => ContentSafetyChecker.checkSafety(content)

// 预设过滤配置
export const FilterPresets = {
  // 严格模式：过滤所有内容
  strict: {
    removeErrors: true,
    filterSensitive: true,
    fixFormat: true,
    validateMedical: true,
    logFiltering: true
  },
  
  // 标准模式：平衡过滤
  standard: {
    removeErrors: true,
    filterSensitive: true,
    fixFormat: true,
    validateMedical: false,
    logFiltering: false
  },
  
  // 宽松模式：仅过滤错误
  lenient: {
    removeErrors: true,
    filterSensitive: false,
    fixFormat: true,
    validateMedical: false,
    logFiltering: false
  },
  
  // 调试模式：不过滤，仅记录
  debug: {
    removeErrors: false,
    filterSensitive: false,
    fixFormat: false,
    validateMedical: false,
    logFiltering: true
  }
}